package com.luych.toolbox.base.service.controller;

import com.luych.toolbox.base.service.entity.Script;
import com.luych.toolbox.base.service.service.ScriptService;
import com.luych.toolbox.common.enums.ScriptType;
import com.luych.toolbox.common.feign.intf.base.service.ScriptFeign;
import com.luych.toolbox.common.feign.param.base.service.ScriptParam;
import com.luych.toolbox.common.feign.view.base.service.ScriptTypeView;
import com.luych.toolbox.common.feign.view.base.service.ScriptView;
import com.luych.toolbox.common.page.CommonPageParam;
import com.luych.toolbox.common.page.CommonPageResult;
import com.luych.toolbox.common.page.CommonSort;
import com.luych.toolbox.common.page.PageResult;
import com.luych.toolbox.common.service.base.BaseController;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Api(tags = "脚本")
@RestController
@RequestMapping("/script")
public class ScriptController
        extends BaseController<ScriptView, ScriptParam, Script>
        implements ScriptFeign {

    private final ScriptService scriptService;

    @Autowired
    public ScriptController(ScriptService scriptService) {
        super(scriptService);
        this.scriptService = scriptService;
    }

    @Override
    public CommonPageResult<ScriptView> pageByKeyword(long pageSize, long pageNumber, String sort, String order, String keyword) {
        CommonPageParam commonPageParam = CommonPageParam.getInstance().setPageSize(pageSize).setPageNumber(pageNumber);
        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            commonPageParam.addSort(CommonSort.getInstance().setSort(sort).setOrder(order));
        }
        PageResult<ScriptView> pageResult = scriptService.pageByKeyword(keyword, commonPageParam);
        return CommonPageResult.getInstance(pageResult);
    }

    @Override
    public CommonPageResult<ScriptTypeView> listType() {
        List<ScriptTypeView> scriptTypeViews = new ArrayList<>();
        for (ScriptType scriptType : ScriptType.values()) {
            ScriptTypeView scriptTypeView = new ScriptTypeView();
            scriptTypeView.setValue(scriptType.name());
            scriptTypeView.setName(scriptType.name());
            scriptTypeViews.add(scriptTypeView);
        }
        CommonPageResult<ScriptTypeView> commonPageResult = new CommonPageResult<>();
        commonPageResult.setTotal(scriptTypeViews.size());
        commonPageResult.setRecords(scriptTypeViews);
        return commonPageResult;
    }
}
